// pages/draw/draw.js
import { COLORS, TYPE } from "../../constant/constant";
import { getDrawBoardById, addMember } from "../../api/api";
import { getUserInfo, linkToHome, showDialog } from "../../utils/utils";

const db = wx.cloud.database();
let watcher;

let DrawBoard;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    drawBoardId: "",
    colors: COLORS,
    curActiveType: TYPE.DRAW, // 当前选中的类型 (draw / eraser)
    curActiveColor: "rgb(0, 0, 0)", // 当前选中的颜色
    curActiveColorId: "black",
    curCustomizeColor: "rgb(255, 255, 255)",
    showColorPicker: false,
    curSize: 1,
    bgColor: "#fff",
    drawBoardData: {
      title: "无标题图片",
    },
    showInviteDialog: false,
    inviteAuth: "view", // 邀请权限 view 可查看 edit 可编辑
    curUserInfo: {
      auth: "view",
      isOwner: false,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let { id, auth } = options;
    if (!id) {
      linkToHome();
      return;
    }

    // 获取当前用户信息
    getUserInfo(false)
      .then(async (userInfo) => {
        wx.showLoading({
          title: "画板数据加载中",
        });

        if (auth) {
          // 新增成员
          await addMember(id, auth, userInfo);
        }

        // 初始化画板
        await this.initDrawBoard(id);

        // 监听画板数据是否发生改变
        this.watchBoardChange(id);
      })
      .catch(() => {
        linkToHome();
      });
  },
  onUnload: async function () {
    // 关闭数据监听
    watcher.close();
    if (this.data.curUserInfo.auth === "edit") {
      // 上传图片
      try {
        await DrawBoard.updateImg();
      } catch (err) {
        console.error(err);
      }
    }
  },
  /**
   * 邀请好友
   */
  onShareAppMessage: function ({ from }) {
    if (from === "button") {
      return {
        title: `${this.data.drawBoardData.owner.nickName}邀请你来一起画画啦~`,
        path: `/pages/draw/draw?id=${this.data.drawBoardId}&auth=${this.data.inviteAuth}`,
        imageUrl: "../../images/invite.png",
      };
    }
  },
  initDrawBoard: async function (id) {
    // 获取画板数据
    const { drawBoardData, curUserInfo } = await getDrawBoardById(id);

    this.setData(
      {
        drawBoardId: id,
        drawBoardData,
        curUserInfo,
      },
      () => {
        // 数据赋值成功后关闭加载
        wx.hideLoading();
      }
    );
    DrawBoard = this.selectComponent(".draw-board");

    wx.setNavigationBarTitle({
      title: drawBoardData.title,
    });
  },
  watchBoardChange: async function (id) {
    const that = this;
    // 监听画板数据是否发生改变, 是的话更新数据
    watcher = await db
      .collection("drawBoards")
      .where({
        _id: id,
      })
      .watch({
        onChange: function ({ docs, type }) {
          // 初始值不需要更新
          if (type === "init") return;
          let drawBoardData = docs[0];
          let curVersion = DrawBoard.getCurVersion();
          if (curVersion < drawBoardData.version) {
            // 如果当前版本小于线上版本, 更新数据
            that.setData({
              drawBoardData,
            });
          }
        },
        onError: function (err) {
          console.error("the watch closed because of error", err);
        },
      });
  },

  /**
   * 修改当前尺寸
   */
  changeSize: function (e) {
    this.setData({
      curSize: e.detail.value,
    });
  },

  /**
   * 选中颜色
   */
  checkColor: function (e) {
    // 点击自定义颜色
    if (e.currentTarget.id === "customize") {
      DrawBoard.hideCanvas(); // 将 canvas 显示为 image, 隐藏 canvas, 防止遮住取色器
    }
    this.setData({
      curActiveColor: this.data.colors[e.currentTarget.id],
      curActiveColorId: e.currentTarget.id,
      curActiveType: TYPE.DRAW,
      showColorPicker: e.currentTarget.id === "customize",
    });
  },

  /**
   * 选中自定义颜色
   */
  changeColor: function (e) {
    this.setData({
      curActiveColor: e.detail.color,
      curCustomizeColor: e.detail.color,
      "colors.customize": e.detail.color,
    });
  },

  /**
   * 关闭取色器
   */
  closePicker: function () {
    this.setData({
      showColorPicker: false,
    });
    DrawBoard.showCanvas(); // 重新展示 canvas
  },

  /**
   * 选中橡皮擦
   */
  checkEraser: function () {
    this.setData({
      curActiveType: TYPE.ERASER,
      curActiveColorId: "",
      curActiveColor: this.data.bgColor,
    });
  },

  /**
   * 保存图片到本地
   */
  saveImg: function () {
    DrawBoard.saveImg();
  },
  /**
   * 重置画板
   */
  reset: function () {
    showDialog({
      title: "提示",
      content: "此操作将清空面板所有内容，且无法撤回，请谨慎操作！",
      showCancel: true,
      confirmText: "确认",
      successCb: () => DrawBoard.reset(),
    });
  },

  /**
   * 撤回上一步操作
   */
  revoke: function () {
    DrawBoard.revoke();
  },

  /**
   * 邀请好友
   */
  invite: function () {
    DrawBoard.hideCanvas(); // 将 canvas 显示为 image, 隐藏 canvas, 防止遮住弹窗
    this.setData({
      showInviteDialog: true,
    });
  },

  changeInviteAuth: function (e) {
    this.setData({
      inviteAuth: e.detail.value,
    });
  },

  /**
   * 关闭邀请弹窗
   */
  closeInviteDialog: function (e) {
    this.setData({
      showInviteDialog: false,
    });
    DrawBoard.showCanvas(); // 重新展示 canvas
  },

  /**
   * 关闭弹窗回调函数
   */
  closeInviteDialog: function () {
    DrawBoard.showCanvas(); // 重新展示 canvas
  },
});
